package com.jingdianjichi.subject.infra.basic.utils;

import com.alibaba.druid.filter.config.ConfigTools;
import com.mysql.cj.util.StringUtils;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * 数据库加密util
 *
 * @author Richard
 * @date 2024/2/12 15:59
 */
public class DruidEncryptUtil {

    private static String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMi64SlrBQOxJwv4a419ZgY09czgpltrJcwAtXw9cTIYjXRiAAzyGIdFFZBmR5CCuQsruWjmXCm54HvVTxcBmHUCAwEAAQ==";

    private static String privateKey = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAyLrhKWsFA7EnC/hrjX1mBjT1zOCmW2slzAC1fD1xMhiNdGIADPIYh0UVkGZHkIK5Cyu5aOZcKbnge9VPFwGYdQIDAQABAkAgzyrucienqtUPB9PMlKqQaSekDTQjzSeoaJVBcWmHHmHTngT1WxszA9xM4dWJZsmGkik/pB2Y2pfLafbU5oohAiEA+MlhQ+4PL1T72UAZWN4rHq9SkCL4r8QOpLJoiTLvSbcCIQDOjMyG487SrmOixbv0Wt2/IUG+vRnnWvU1JJRLjt1fMwIgNmQQl8FcIIT76qtQ31TzKGo8Krb6l7LNYMSAhj5UglECIECUn2JRmhofcoGzR4goXQrkkBTeNVo0A1UhYciaG7cnAiEA7O5s1C4Fb92T4KqJNrqaQxtVYBcO0CsuPXW3As2DQ1M=";

    static {
        try {
            if (StringUtils.isNullOrEmpty(privateKey) && StringUtils.isNullOrEmpty(publicKey)){
                String[] keyPair = ConfigTools.genKeyPair(512);

                privateKey = keyPair[0];
                System.out.println("privateKey:" + privateKey);
                publicKey = keyPair[1];
                System.out.println("publicKey:" + publicKey);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
    }

    public static String encrypt(String plainText) throws Exception {
        String encrypt = ConfigTools.encrypt(privateKey, plainText);
        System.out.println("encrypt:" + encrypt);
        return encrypt;
    }

    public static String decrypt(String encryptText) throws Exception {
        String decrypt = ConfigTools.decrypt(publicKey,encryptText);
        System.out.println("encrypt:" + decrypt);
        return decrypt;
    }

    public static void main(String[] args) throws Exception {
        //使用私钥和明文进行加密，并将密文返回
        String encrypt = encrypt("Wing1Q2W#E");
        System.out.println("encrypt:" + encrypt);
        //使用密文和公钥进行解密，并返回解密之后的密码
        String decrypt = decrypt(encrypt);
        System.out.println("decrypt" + decrypt);
    }
}
